package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;


    /**用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理各种业务异常：1、地址簿为空。2、购物车数据为空
        //1判断地址簿是否为空
        AddressBook addressBook = addressMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            //地址簿为空抛出业务异常
            throw  new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
       /* Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = AddressBook.builder().id(addressBookId).build();
        List<AddressBook> allAddress = addressMapper.getAllAddress(addressBook);
        AddressBook addressBook1 = allAddress.get(0);
        if (addressBook1 == null){
            //地址簿为空抛出业务异常
            throw  new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }*/


        //判断购物车是否为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.size()==0){
            //购物车为空,抛出异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);

        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        //使用时间戳作为订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);

        orderMapper.insert(orders);



        List<OrderDetail> orderDetailslist = new ArrayList<>();
        //向订单明细表插入多条数据
        for (ShoppingCart cart : list) {
            //订单明细
            OrderDetail orderDetail = new OrderDetail();

            BeanUtils.copyProperties(cart,orderDetail);
            //设置当前订单明细关联的订单id
            orderDetail.setOrderId(orders.getId());

            orderDetailslist.add(orderDetail);

        }

        //批量插入到订单明细表中
        orderDetailMapper.insertbatch(orderDetailslist);


        //下单成功，清空购物车
        shoppingCartMapper.clean(userId);


        //封装Vo返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

        return orderSubmitVO;
    }



    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        /*JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;*/
        paySuccess(ordersPaymentDTO.getOrderNumber());



        String orderNumber = ordersPaymentDTO.getOrderNumber(); //订单号

        Long orderid = orderMapper.getorderId(orderNumber);//根据订单号查主键



        JSONObject jsonObject = new JSONObject();//本来没有2

        jsonObject.put("code", "ORDERPAID"); //本来没有3

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);

        vo.setPackageStr(jsonObject.getString("package"));

        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改

        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付

        Integer OrderStatus = Orders.TO_BE_CONFIRMED; //订单状态，待接单

        //发现没有将支付时间 check_out属性赋值，所以在这里更新

        LocalDateTime check_out_time = LocalDateTime.now();



        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, orderid);

        //通过websocket向客户端推送消息
        //三个参数 type 、orderId 、 content
        Map map = new HashMap<>();
        map.put("type",1);//1表示来单提醒  2 表示催单
        map.put("orderId",orderid);
        map.put("content","订单号:" + orderNumber);

        //将java对象转为json字符串
        String json = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(json);

        return vo;  //  修改支付方法中的代码
    }

    /**
     * 注意：此方法没有使用到
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);



    }


    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        //page中封装的是查询到的所有的符合条件的订单信息
        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);

        //list中 data中record的封装
        List<OrderVO> list = new ArrayList<>();

        for (Orders orders : page) {
            //orders是一个订单对象，包含了订单的信息
            // 获得订单id
            Long ordersId = orders.getId();

            //获得订单明细
            List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(ordersId);

            //封装到一个订单VO对象中
            OrderVO orderVO = new OrderVO();
            //把订单信息复制给订单VO对象中
            BeanUtils.copyProperties(orders,orderVO);

            //把订单详情封装到list中的VO对象中
            orderVO.setOrderDetailList(orderDetail);

            //将本次封装成功的OrderVo对象添加到list集合中
            list.add(orderVO);

        }

        return new PageResult(page.getTotal(),list);
    }

    /**查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public OrderVO getOrderDetail(Long id) {
        Orders orders = orderMapper.getByOrderId(id);

        List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(id);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);

        Long addressBookId = orderVO.getAddressBookId();
        AddressBook addressBook = AddressBook.builder().id(addressBookId).build();
        List<AddressBook> allAddress = addressMapper.getAllAddress(addressBook);

        AddressBook address = allAddress.get(0);

        if (address != null){
            /*String s = allAddress.toString();*/
            //去除重写tostring方法后两边的[];
            String s = StringUtils.strip(allAddress.toString(),"[]");
            orderVO.setAddress(s);
        }



        orderVO.setOrderDetailList(orderDetail);

        return orderVO;



    }

    /**用户取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        Orders order = orderMapper.getByOrderId(id);
        //校验订单是否存在
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Integer status = order.getStatus();
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (status > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (status == Orders.PENDING_PAYMENT || status == Orders.TO_BE_CONFIRMED){
            //待支付和待接单状态，可以直接取消订单
            //更新取消时间、取消原因、订单状态
            order.setStatus(Orders.CANCELLED);
            order.setCancelTime(LocalDateTime.now());
            order.setCancelReason("用户取消");
            orderMapper.update(order);
        }

    }

    /**管理端取消订单
     *
     * @param ordersCancelDTO
     */

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Long orderId = ordersCancelDTO.getId();
        Orders order = orderMapper.getByOrderId(orderId);
        //校验订单是否存在
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        Orders orders = Orders.builder()
                .id(orderId)
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .build();

        orderMapper.update(orders);


    }

    /**派送订单
     *订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        //校验订单是否存在
        if (orders == null || orders.getStatus() != Orders.CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders order = Orders.builder()
                .status(Orders.DELIVERY_IN_PROGRESS)
                .id(id)
                .build();
        orderMapper.update(order);
    }

    /**完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        if (orders == null || orders.getStatus() != Orders.DELIVERY_IN_PROGRESS ){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders order = Orders.builder().status(Orders.COMPLETED).id(id).build();
        orderMapper.update(order);
    }

    /**客户催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //根据订单id查询订单
        Orders order = orderMapper.getByOrderId(id);
        //校验订单是否存在
        if (order == null ){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap<>();
        map.put("type",2);//2表示客户催单
        map.put("orderId",id);
        map.put("content","订单号："+order.getNumber());

        //将map对象转换位json字符
        String json = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(json);
    }

    /**再来一单
     *
     * @param id
     */
    @Override
    public void againorder(Long id) {
        Long userId = BaseContext.getCurrentId();
        //查询到此订单中的菜品详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        //将菜品放入购物车
         List<ShoppingCart> shoppingCart = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart1 = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart1);
            shoppingCart1.setUserId(userId);
            shoppingCart1.setCreateTime(LocalDateTime.now());
            shoppingCart.add(shoppingCart1);
        }

        //从购物车中下单,插入到数据库
        shoppingCartMapper.insertBatch(shoppingCart);


    }

    /**统计各状态单量
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {

        //待接单
      Integer toBeConfirmed = orderMapper.statistics(Orders.TO_BE_CONFIRMED);
      //待派送
      Integer confirmed = orderMapper.statistics(Orders.CONFIRMED);
      //派送中
      Integer deliveryInProgress = orderMapper.statistics(Orders.DELIVERY_IN_PROGRESS);

      OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
      orderStatisticsVO.setConfirmed(confirmed);
      orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
      orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void takeOrders(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder().status(Orders.CONFIRMED).id(ordersConfirmDTO.getId()).build();
        orderMapper.update(orders);
    }

    /**拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrders(OrdersRejectionDTO ordersRejectionDTO) {
        Long orderId = ordersRejectionDTO.getId();
        Orders order = orderMapper.getByOrderId(orderId);
        if (order == null || order.getStatus() != Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        else {
            Orders orders = Orders.builder()
                    .status(Orders.CANCELLED)
                    .rejectionReason(ordersRejectionDTO.getRejectionReason())
                    .cancelTime(LocalDateTime.now())
                    .id(orderId)
                    .build();
            orderMapper.update(orders);
        }

    }

    /**
     * 管理端订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult serachOrder(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);

        //获得订单的地址
        for (Orders orders : page) {
            Long addressBookId = orders.getAddressBookId();
            AddressBook addressBook = AddressBook.builder().id(addressBookId).build();
            //地址信息
            List<AddressBook> allAddress = addressMapper.getAllAddress(addressBook);
            String address = StringUtils.strip(allAddress.toString(), "[]");
            orders.setAddress(address);
        }


        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }



}
